package kr.ac.hanyang.cs.park;

import java.util.ArrayList;
import kr.ac.hanyang.cs.park.DBConstants.Task;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class TaskList extends ListActivity {
    private ArrayList<TaskInfo> allTasks				= null;
	private SQLiteDatabase taskDB						= null;
	private TaskListAdapter taskListAdapter				= null;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    // TODO Auto-generated method stub
	    updateTaskList();

	    taskListAdapter									= new TaskListAdapter(this, R.layout.mainitems, allTasks);
        setListAdapter(taskListAdapter);
    }

	@Override
	protected void onResume() {
		super.onResume();

		updateTaskList();

	    taskListAdapter									= new TaskListAdapter(this, R.layout.mainitems, allTasks);
        setListAdapter(taskListAdapter);
	}	


	private void updateTaskList() {
		TaskInfo runTask								= new TaskInfo();
		TaskInfo playTask								= new TaskInfo();
		TaskInfo descTask								= new TaskInfo();

		// get all tasks
		runTask.setDebug(true);
		allTasks										= runTask.getTaskInfo(this);


		// add item (new task)
//		Drawable addIcon								= getResources().getDrawable(android.R.drawable.ic_menu_add);
//		addNewTask.setIcon(addIcon);
//		addNewTask.setTaskName("새로운 작업 등록");
//		addNewTask.setDescription("새로운 행동을 선택한 후 명령어를 등록합니다.");
//		addNewTask.setTaskType(TaskType.NEW_TASK);
//		allTasks.add(addNewTask);

		// add item (desc task)
		Drawable descIcon								= getResources().getDrawable(android.R.drawable.ic_menu_help);
		descTask.setIcon(descIcon);
		descTask.setTaskName("사용법 설명");
		descTask.setDescription("프로그램 사용법에 대한 설명을 봅니다.");
		descTask.setTaskType(TaskType.DESC_TASK);
		allTasks.add(descTask);


		// add item (play task)
		Drawable playIcon								= getResources().getDrawable(android.R.drawable.ic_menu_info_details);
		playTask.setIcon(playIcon);
		playTask.setTaskName("명령어 예제");
		playTask.setDescription("명령어의 예제를 들을 수 있습니다.");
		playTask.setTaskType(TaskType.PLAY_TASK);
		allTasks.add(playTask);

		
		// add item (run task)
		Drawable runIcon								= getResources().getDrawable(android.R.drawable.ic_btn_speak_now);
		runTask.setIcon(runIcon);
		runTask.setTaskName("음성 실행");
		runTask.setDescription("음성 명령어로 작업을 실행합니다.");
		runTask.setTaskType(TaskType.RUN_TASK);
		allTasks.add(runTask);
	}


	private void deleteTask(int taskNo) {
		TaskInfo taskToDelete							= allTasks.get(taskNo);
		
		if (taskToDelete == null || taskNo == -1)
			return;

	    taskDB											= (new TaskDBHelper(this)).getWritableDatabase();
		taskDB.delete(Task.TABLE_NAME, Task.TASKID + "=" + taskToDelete.getId(), null);
		taskDB.close();

		updateTaskList();

	    taskListAdapter									= new TaskListAdapter(this, R.layout.mainitems, allTasks);
        setListAdapter(taskListAdapter);
	}
	

    private class TaskListAdapter extends ArrayAdapter<TaskInfo> {
    	private ArrayList<TaskInfo> items;
    	private int selectedTaskNo						= -1;



    	public TaskListAdapter(Context context, int textViewResourceId, ArrayList<TaskInfo> items) {
    		super(context, textViewResourceId, items);
    		this.items									= items;
    	}


    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View v										= convertView;

    		if (v == null) {
    			LayoutInflater vi						= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			v										= vi.inflate(R.layout.mainitems, null);
            }


    		TaskInfo task								= items.get(position);

    		if (task != null) {
    			ImageView icon							= (ImageView)v.findViewById(R.id.main_imgIcon);
    			TextView name							= (TextView) v.findViewById(R.id.main_txtTaskName);
    			TextView desc							= (TextView) v.findViewById(R.id.main_txtDescription);

    			if (icon != null)
    				icon.setImageDrawable(task.getIcon());

    			if (name != null)
    				name.setText(task.getTaskName());

    			if (desc != null)
    				if (task.getDescription().equals(""))
    					desc.setText(task.getTaskOption());
    				else
    					desc.setText(task.getDescription());

    			// 현재 item의 position을 버튼에 tagging한 후, 클릭 시 이벤트 리스터에 넘김
    			v.setTag(position);
    			v.setOnClickListener(itemClickListener);
    			//v.setOnLongClickListener(itemLongClickListener);
            }

            return v;
    	}

    	// ask for delete when long click
    	private View.OnLongClickListener itemLongClickListener = new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
    			selectedTaskNo							= (Integer) v.getTag();


				AlertDialog.Builder delDlg				= new AlertDialog.Builder(v.getContext());

				delDlg.setTitle("삭제 확인");
				delDlg.setMessage("삭제하시겠습니까?");

				delDlg.setPositiveButton("예", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// task 삭제
						deleteTask(selectedTaskNo);
						dialog.dismiss();
					}
				});

				delDlg.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

				delDlg.show();

				return false;
			}
		};

		// run
		private View.OnClickListener itemClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				TaskInfo selectedTask					= items.get((Integer) v.getTag());
				CastSpell cast							= new CastSpell(TaskList.this);
				Intent intent							= null;

				switch (selectedTask.getTaskType()) {
					case NEW_TASK:
						intent							= new Intent(TaskList.this, NewTask.class);
						startActivity(intent);
						break;

					case DESC_TASK:
						intent							= new Intent(TaskList.this, DescTask.class);
						startActivity(intent);
						break;

					case PLAY_TASK:
						intent							= new Intent(TaskList.this, PlayTask.class);
						startActivity(intent);
						break;

					case RUN_TASK:
						intent							= new Intent(TaskList.this, RunTask.class);
						startActivity(intent);

					// LAUNCH TASK HERE
					default:
						cast.castSkill(selectedTask.getTaskType(), selectedTask.getTaskOption());
						break;
				}

			}
			
		};

    }
}
